<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Moneylog, Team, UserAuth, UserSafety, SignLog, Config, MachineLog, ContractOrder, ContractSell};
use think\Facade\Config as Configs;
use app\facade\Mns;
use think\Validate;
use think\Db;

class User extends Base
{
    //注册账号
    public function register()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'nickname' => 'require|chsAlphaNum',
            'mobile' => 'require',
            'code' => 'require',
            'invit' => 'require|gt:0',
            'password' => 'require',
            'trade' => 'require',
        ], [
            'nickname.require' => '昵称不能为空',
            'chsAlphaNum.require' => '昵称必须是汉字、字母或数字',
            'mobile.require' => '手机号不能为空',
            'code.require' => '手机验证码不能为空',
            'invit.require' => '邀请码不能为空',
            'invit.gt' => '邀请码错误',
            'password.require' => '登录密码不能为空',
            'trade.require' => '支付密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
            $this->result([], 1, '手机号格式不正确');
        }
        //识别验证码是否正确
        if (!(new Mns())->checkCode($data['code'], $data['mobile'])) {
            $this->result([], 1, '手机验证码错误');
        }
        //判断邀请码是否存在
        $code = (new Users())->where('code', $data['invit'])->find();
        if (empty($code)) {
            $this->result([], 1, '邀请码错误');
        }
        //判断手机号码是否已存在
        $user = (new Users())->where('mobile', $data['mobile'])->find();
        if (!empty($user)) {
            $this->result([], 1, '手机号码已注册');
        }
        if (empty($code['structure'])) {
            $structure = $code['id'];
        } else {
            $structure = $code['structure'] . ',' . $code['id'];
        }
        $people = explode(',', $structure);
        $people = array_filter($people); //给上级人员增加团队人数
        $people = array_reverse($people);
        $mycode = recode(new Users());
        $teamdata = [];
        Db::startTrans();
        try {
            $id = (new Users())->insertGetId([
                'mobile' => $data['mobile'],
                'nickname' => $data['nickname'],
                'password' => md5(md5($data['password'])),
                'trade' => md5(md5($data['trade'])),
                'code' => $mycode,
                'pid' => $code['id'],
                'ppid' => $code['pid'],
                'structure' => $structure,
                'created' => date('Y-m-d H:i:s')
            ]);
            foreach ($people as $k => $v) {
                $teamdata[] = ['user_id' => $v, 'supe_id' => $id, 'algebra' => ($k + 1), 'dates' => date('Y-m-d')];
            }
            if (!empty($teamdata)) {
                (new Team())->insertAll($teamdata);
            }
            Redis::lPush('lists', $id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result($e->getMessage(), 1, '注册失败，请重试');
        }
        $this->result([], 0, '注册成功');
    }

    //账号登录
    public function Login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '手机号码不能为空',
            'password.require' => '密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
            $this->result([], 1, '手机号格式不正确');
        }
        $user = (new Users())->where(['mobile' => $data['mobile'], 'password' => md5(md5($data['password']))])->find();
        if ($user) {
            $token = md5(md5($user['id'] . $user['code'] . time()));
            Redis::setex($token, 86400 * 5, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }
        $this->result([], 1, '账号或密码错误');
    }

    //忘记密码
    public function Forget()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'code' => 'require',
            'password' => 'require',
        ], [
            'mobile.require' => '登录账号不能为空',
            'code.require' => '验证码不能为空',
            'password.require' => '密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
            $this->result([], 1, '手机号格式不正确');
        }
        //识别验证码是否正确
        if (!(new Mns())->checkCode($data['code'], $data['mobile'])) {
            $this->result([], 1, '手机验证码错误');
        }
        //账号不存在
        $user = (new Users())->where('mobile', $data['mobile'])->find();
        if (empty($user)) {
            $this->result([], 1, '账号不存在');
        }
        if (md5(md5($data['password'])) == $user['password']) {
            $this->result([], 1, '找回密码和不能和原密码一致');
        }
        $res = (new Users())->where('id', $user['id'])->update(['password' => md5(md5($data['password']))]);
        if (!$res) {
            $this->result([], 1, '修改失败，请重试');
        }
        $this->result([], 0, '修改成功');
    }

    public function TradeEdit()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'trade' => 'require',
            'type' => 'require|in:1,2'
        ], [
            'code.require' => '验证码不能为空',
            'trade.require' => '密码不能为空',
            'type.require' => '修改类型必须填写',
            'type.in' => '修改类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = $this->request->user;
        //识别验证码是否正确
        if (!(new Mns())->checkCode($data['code'], $user['mobile'])) {
            $this->result([], 1, '手机验证码错误');
        }
        if ($data['type'] == 1) {
            if (md5(md5($data['trade'])) == $user['password']) {
                $this->result([], 1, '修改密码和不能和原密码一致');
            }
            $res = (new Users())->where('id', $user['id'])->update(['password' => md5(md5($data['trade']))]);
        } else {
            if (md5(md5($data['trade'])) == $user['trade']) {
                $this->result([], 1, '修改密码和不能和原密码一致');
            }
            $res = (new Users())->where('id', $user['id'])->update(['trade' => md5(md5($data['trade']))]);
        }
        if (!$res) {
            $this->result([], 1, '修改失败，请重试');
        }
        $this->result([], 0, '修改成功');
    }

    public function UserAuth()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'card_no' => 'require',
                'cardpos' => 'require',
                'cardrec' => 'require'
            ], [
                'name.require' => '请输入认证名称',
                'card_no.require' => '请输入认证身份证号',
                'cardpos.require' => '身份证正面必须上传',
                'cardrec.require' => '身份证反面必须上传'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $card = (new UserAuth())->where('card_no', $data['card_no'])->count();
            if ($card >= 5) {
                $this->result([], 1, '每个身份证号只可重复使用5次');
            }
            $auth = (new UserAuth())->where('user_id', $this->request->user_id)->find();
            if (!empty($auth) && $auth['status'] == 2) {
                $this->result([], 1, '您已认证，无需重复认证');
            }
            $data['status'] = 1;
            Db::startTrans();
            try {
                if (!empty($auth)) {
                    (new UserAuth())->allowfield(true)->save($data, ['user_id' => $this->request->user_id]);
                } else {
                    $data['user_id'] = $this->request->user_id;
                    (new UserAuth())->allowfield(true)->save($data);
                }
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                $this->result([], 1, '提交失败，请重试');
            }
            $this->result([], 0, '提交成功，请等待审核');
        } else {
            $result = (new UserAuth())->where('user_id', $this->request->user_id)->field('created,updated,user_id', true)->find();
            $this->result($result, 0, '获取成功');
        }
    }


    public function UserSafety()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2,3',
                'name' => 'require',
                'cards' => 'require'
            ], [
                'type.require' => '收款类型不能为空',
                'type.in' => '收款类型错误',
                'name.require' => '用户名不能为空',
                'cards.require' => '卡号|账号|微信号不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['type'] == 3 && empty($data['bank'])) {
                $this->result([], 1, '开户行不能为空');
            }
            if ($data['type'] != 3 && empty($data['images'])) {
                $this->result([], 1, '收款码不能为空');
            }
            $safety = (new UserSafety())->where(['user_id' => $this->request->user_id, 'type' => $data['type']])->find();
            Db::startTrans();
            try {
                if (!empty($safety)) {
                    (new UserSafety())->allowfield(true)->save($data, ['id' => $safety['id']]);
                } else {
                    $data['user_id'] = $this->request->user_id;
                    (new UserSafety())->allowfield(true)->save($data);
                }
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                $this->result([], 1, '提交失败，请重试');
            }
            $this->result([], 0, '提交成功');
        } else {
            $type = $this->request->get('type/d', 0);
            $result = (new UserSafety());
            if ($type) {
                $result = $result->where('type', $type);
            }
            $result = $result->where('user_id', $this->request->user_id)->field('id,created,updated,user_id', true)->select();
            $this->result($result, 0, '获取成功');
        }
    }

    public function Myteam()
    {
        $type = $this->request->get('type/d', '');
        if (empty($type)) {
            $this->result([], 1, '获取失败');
        }
        if ($type == 1) {
            $list['data'] = (new Users())->where(['pid' => $this->request->user_id])->field('mobile,created')->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($list['data'] as $lists) {
                $lists['text'] = '一级会员';
            }
            $list['total'] = (new Users())->where(['pid' => $this->request->user_id])->count();
        } else {
            $list['data'] = (new Users())->where(['ppid' => $this->request->user_id])->field('mobile,created')->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($list['data'] as $lists) {
                $lists['text'] = '二级会员';
            }
            $list['total'] = (new Users())->where(['ppid' => $this->request->user_id])->count();
        }
        $this->result($list, 0, '获取成功');
    }


    public function Attr()
    {
        $attr = $this->request->get('attr', '');
        if (empty($attr)) {
            $this->result([], 1, '请上传头像路径');
        }
        Db::startTrans();
        try {
            (new Users())->where('id', $this->request->user_id)->update(['avatar' => $attr]);
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '修改失败，请重试');
        }
        $this->result([], 0, '修改成功');
    }

    public function SignLog()
    {
        $today = (new SignLog())->where(['user_id' => $this->request->user_id, 'dates' => date('Y-m-d')])->find();
        if (!empty($today)) {
            $this->result([], 1, '今日已签到');
        }
        $money = (new Config())->where('key', 'signgive')->value('value');
        $money = empty($money) ? 0 : $money;
        Db::startTrans();
        try {
            (new SignLog())->insert([
                'user_id' => $this->request->user_id,
                'money' => $money,
                'dates' => date('Y-m-d')
            ]);
            if ($money > 0) {
                (new Users())->MoneyEdit($this->request->user_id, $this->request->user['amount'], $money, 2, 2, '签到赠送');
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '签到失败，请重试');
        }
        $this->result($money, 0, '签到成功');
    }

    public function Info()
    {
        $MachineRewards = (new Config())->where('key', 'machine_rewards')->value('value');
        $MachineRewards = empty($MachineRewards) ? 10 : (int)$MachineRewards;
        if ($MachineRewards < 1) {
            $MachineRewards = 1;
        }
        $tree = [];
        for ($i = 1; $i <= $MachineRewards; $i++) {
            $tree[] = $i;
        }
        $myteam = (new Team())->where(['user_id' => $this->request->user_id, 'algebra' => $tree])->column('supe_id');
        $user = $this->request->user;
        $MachineLog = (new MachineLog())->where(['user_id' => $this->request->user_id, 'status' => 1])->select();
        $machine = 0;
        $endmachine = 0;
        $rewardmachine = 0;
        $todayincome = 0;
        $income = 0;
        foreach ($MachineLog as $machlog) {
            if ($machlog['status'] == 1) {
                $machine += 1;
            }
            if ($machlog['status'] == 2) {
                $endmachine += 1;
            }
            if ($machlog['type'] == 2) {
                $rewardmachine += 1;
            }
            if ($machlog['days'] >= date('Y-m-d')) {
                $rewardmachine += $machlog['todayincome'];
            }
            $income += $machlog['todayincome'];
        }
        $result = [
            'id' => $user['id'],
            'mobile' => $user['mobile'],
            'money' => $user['money'],
            'amount' => $user['amount'],
            'code' => $user['code'],
            'quota' => $user['quota'],
            'assets' => $user['assets'],
            'power' => $user['power'],
            'nickname' => $user['nickname'],
            'avatar' => $user['avatar'],
            'level' => $user['level'],
            'teampower' => 0,
            'machine' => $machine,
            'endmachine' => $endmachine,
            'rewardmachine' => $rewardmachine,
            'todayincome' => $todayincome,
            'income' => $income,
            'reward' => $user['allincome'],
            'cotatol' => (new ContractOrder())->where(['user_id' => $this->request->user_id, 'status' => 3, 'income_status' => 2])->sum('price')
                + (new ContractSell())->where(['user_id' => $this->request->user_id, 'status' => [1, 2]])->sum('price'),
            'share' => (new Config())->where('key', 'share')->value('value') . '?code=' . $user['code']
        ];
        if (count($myteam) > 0) {
            $result['teampower'] = (new Users())->where(['id' => $myteam])->sum('power');
        }
        $this->result($result, 0, '签到成功');
    }
}
